const message = document.getElementById('message');
const content = document.querySelector('.content');
const sendBtn = document.getElementById('send');

message.onkeydown = function (e) {
    //判断按下的是不是enter按钮 如果是则发送数据
    if (e.keyCode === 13) {
        var value = message.value;
        // 判断当前输入框是否有信息  有的话发送出去
        if (value) {
            renderMessage('mine', value);
            this.value = "";
            sendMessage(value);
        }
    }
}

sendBtn.onclick = function () {
    if (message.value) {
        renderMessage('mine', message.value);
        message.value = "";
        sendMessage(message.value);
    }
}

//发出网络请求
function sendMessage(text) {
    ajax({
        method:"get",
        url:"https://developer.duyiedu.com/edu/turing/chat",
        data:"text="+text,
        success:function (data) {
            console.log(data)
            renderMessage('robot', data.text);
        }
    })
}

//渲染信息  who是谁说话 text说了什么
function renderMessage(who,text){
    console.log(who,text);
    const dom = document.createElement('div');
    const img = new Image();
    const textDom = document.createElement('div');
    img.className = 'avator';
    textDom.className = 'text';
    textDom.innerText = text;

    if (who === 'mine') {
        img.src = "./img/3.png";
        dom.className = 'mine';
    } else {
        img.src = "./img/dog1.jpg";
        dom.className = 'robot';
    }
    dom.appendChild(img);
    dom.appendChild(textDom);
    content.appendChild(dom);
    //srollHeight:代表的是当前内容区正在没有滚动条的时候，里面元素撑开的大小
    //clienHeight:代表是当前内容区视口的高度
    content.scrollTo(0, content.scrollHeight - content.clientHeight);
}